#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF导出功能演示脚本
展示如何使用ExportManager进行PDF批量导出
"""

import os
import sys
import logging
from datetime import datetime, timedelta

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.utils.export_manager import ExportManager
from src.models.models import Sample, SampleInfo, Results, ImageInfo, ModeInfo

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

def create_demo_samples():
    """创建演示用的样本数据"""
    samples = []
    
    # 创建5个演示样本
    for i in range(5):
        # 生成时间
        base_time = datetime.now() - timedelta(hours=i*2)
        
        # 创建样本信息
        sample_info = SampleInfo(
            sample_number=f"DEMO{i+1:03d}",
            patient_name=f"演示患者{i+1}",
            patient_age=30 + i*5,
            patient_gender="男" if i % 2 == 0 else "女",
            position=f"位置{i+1}",
            sample_type_name="血液样本",
            report_id=f"RPT{i+1:03d}",
            datetime=base_time.strftime("%Y-%m-%d %H:%M:%S")
        )
        
        # 创建检测结果
        results = Results(
            HbA1a=f"{5.2 + i*0.1:.1f}",
            HbA1b=f"{0.8 + i*0.05:.2f}",
            HbF=f"{0.5 + i*0.1:.1f}",
            LA1c=f"{6.1 + i*0.2:.1f}",
            HbA1c=f"{5.8 + i*0.15:.1f}",
            HbA0=f"{87.6 - i*0.3:.1f}",
            eAG=f"{120 + i*5}",
            A2=f"{2.8 + i*0.1:.1f}",
            HbE=f"{0.0}",
            HbD=f"{0.0}",
            HbS=f"{0.0}",
            HbC=f"{0.0}",
            p3=f"{0.0}",
            v_win=f"{0.0}",
            TIME=[f"{1.2 + i*0.1:.1f}", f"{2.1 + i*0.1:.1f}", f"{3.0 + i*0.1:.1f}"],
            AREA=[f"{1000 + i*50}", f"{800 + i*40}", f"{600 + i*30}"]
        )
        
        # 创建图片信息
        image_info = ImageInfo(
            filename=f"sample_{i+1}.jpg",
            path=f"/path/to/image_{i+1}.jpg",
            size=f"{1024 + i*100}KB"
        )
        
        # 创建模式信息
        mode_info = ModeInfo(
            mode_name="标准模式",
            mode_description="标准检测模式",
            test_count=15,
            test_items=["HbA1a", "HbA1b", "HbF", "LA1c", "HbA1c", "HbA0", "eAG", "A2", "HbE", "HbD", "HbS", "HbC", "p3", "v_win", "TIME", "AREA"]
        )
        
        # 创建样本对象
        sample = Sample(
            id=f"DEMO{i+1:03d}",
            sample_info=sample_info,
            results=results,
            image=image_info,
            mode_info=mode_info,
            machine_model="DEMO-2000",
            machine_id=f"DEMO{i+1:03d}",
            analysis_mode="自动",
            protocol="TCP",
            receive_time=base_time,
            created_time=base_time - timedelta(minutes=30),
            status="已完成"
        )
        
        samples.append(sample)
    
    return samples

def main():
    """主函数"""
    print("🚀 PDF导出功能演示")
    print("=" * 50)
    
    try:
        # 创建导出管理器
        print("📋 创建导出管理器...")
        export_manager = ExportManager()
        
        # 设置医院信息
        print("🏥 设置医院信息...")
        export_manager.set_hospital_info(
            name="小苏科技演示医院",
            address="北京市朝阳区演示路123号",
            contact="010-12345678"
        )
        
        # 创建演示样本
        print("🧪 创建演示样本数据...")
        samples = create_demo_samples()
        print(f"✅ 成功创建 {len(samples)} 个演示样本")
        
        # 显示样本信息
        print("\n📊 样本信息预览:")
        for i, sample in enumerate(samples, 1):
            print(f"  样本{i}: {sample.sample_info.patient_name} - {sample.sample_info.sample_number}")
        
        # 生成输出文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_file = f"demo_pdf_export_{timestamp}.zip"
        
        print(f"\n🚀 开始导出PDF到: {output_file}")
        print("⏳ 请稍候，正在生成PDF文件...")
        
        # 执行PDF导出
        success = export_manager.export_samples_to_pdf_zip(samples, output_file)
        
        if success:
            print(f"✅ PDF导出成功: {output_file}")
            
            # 显示文件信息
            if os.path.exists(output_file):
                file_size = os.path.getsize(output_file) / 1024  # KB
                print(f"📁 文件大小: {file_size:.2f} KB")
                
                # 显示ZIP内容
                import zipfile
                with zipfile.ZipFile(output_file, 'r') as zip_file:
                    file_list = zip_file.namelist()
                    print(f"📋 ZIP文件内容:")
                    for file_name in file_list:
                        print(f"  - {file_name}")
            
            print("\n🎉 演示完成！")
            print("💡 提示：您可以在文件管理器中查看生成的ZIP文件")
            
        else:
            print("❌ PDF导出失败")
            return 1
            
    except Exception as e:
        print(f"❌ 演示过程中出现错误: {e}")
        logging.error(f"演示错误: {e}", exc_info=True)
        return 1
    
    return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)
